from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

def load_cookies_from_file(filename):
    """从文件中加载 cookies"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            cookies_str = f.read().strip()
        
        # 解析 cookies 字符串
        cookies_list = []
        for cookie_pair in cookies_str.split(';'):
            if '=' in cookie_pair:
                name, value = cookie_pair.strip().split('=', 1)
                cookies_list.append({
                    'name': name.strip(),
                    'value': value.strip(),
                    'domain': '.jd.com',  # 京东域名
                    'path': '/'
                })
        return cookies_list
    except Exception as e:
        print(f"加载 cookies 文件出错: {e}")
        return []

def attach_to_chrome_with_cookies():
    """连接到已经打开的Chrome浏览器并注入cookies"""
    try:
        print("尝试连接Chrome...")
        chrome_options = Options()
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
        chrome_driver_path = r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
        service = Service(executable_path=chrome_driver_path)
        driver = webdriver.Chrome(service=service, options=chrome_options)
        print("Chrome连接成功！")

        # 加载并注入 cookies
        print("开始注入 cookies...")
        cookies = load_cookies_from_file('cookies.txt')
        
        # 先访问京东域名，然后才能设置 cookies
        driver.get("https://www.jd.com")
        
        # 注入每个 cookie
        for cookie in cookies:
            try:
                driver.add_cookie(cookie)
                print(f"成功注入 cookie: {cookie['name']}")
            except Exception as e:
                print(f"注入 cookie {cookie['name']} 失败: {e}")
        
        print("Cookies 注入完成！")
        return driver
    except Exception as e:
        print(f"Chrome连接失败: {e}")
        raise

if __name__ == "__main__":
    # 测试代码
    driver = attach_to_chrome_with_cookies()
    print("测试访问京东...")
    driver.get("https://www.jd.com")
    input("按回车键退出...")
    driver.quit()
